package com.hzvdvmc.autosale.seriaport;

import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.hzvdvmc.autosale.MyApp;
import com.hzvdvmc.autosale.constant.ResultEnum;
import com.hzvdvmc.autosale.socket.TempDataHelper;
import com.hzvdvmc.autosale.socket.event.CommonEvent;
import com.hzvdvmc.autosale.socket.manager.CheckNumUtil;
import com.hzvdvmc.autosale.socket.manager.CmdRequestManager;
import com.hzvdvmc.autosale.socket.manager.CmdResponseManager;
import com.hzvdvmc.autosale.util.EncodeUtil;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.StringUtil;
import com.hzvdvmc.autosale.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * Created by william on 2018/1/2.
 * 串口指令 响应处理者
 */

public class SerialCmdResponseManager {
    public static SerialCmdResponseManager instance;
    private SerialCmdResponseManager.ResopnseCallback resopnseCallback;
    private String reqeustCmdValue;//请求编号
    private android.os.Handler handler = new android.os.Handler(Looper.getMainLooper());


    public void setResopnseCallback(ResopnseCallback resopnseCallback) {
        this.resopnseCallback = resopnseCallback;
    }

    public void setReqeustCmdValue(String reqeustCmdValue) {
        this.reqeustCmdValue = reqeustCmdValue;
    }

    public static SerialCmdResponseManager getInstance() {
        if (instance == null) {
            instance = new SerialCmdResponseManager();
        }
        return instance;
    }

    /**
     * 根据异或条件校验数据可靠性
     *
     * @return
     */
    public static boolean checkResponse(String response) {
        //响应的异或数据
        String checkNumResp = response.substring(6, 8);
        //解密后的消息体
//        String comandAndData = EncodeUtil.decoded(response.substring(8));
        String comandAndData = response.substring(8);
        LogUtil.i("serialport", "收到串口指令解密后：" + comandAndData);
        String command = comandAndData.substring(0, 2);
        String data = comandAndData.substring(2);
        if (checkNumResp.equals(CheckNumUtil.getCheckNumHex(command, data))) return true;
        return false;
    }

    public void handleResponse(String response) throws Exception {
        LogUtil.i("{SerialCmdResponseManager}[handleResponse]");
        boolean isValid = false;
        try {
            isValid = checkResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (isValid) {
            //暂时不加密
//            String comandAndData = EncodeUtil.decoded(response.substring(8));
            String comandAndData = response.substring(8);
            final String command = comandAndData.substring(0, 2).toUpperCase();
            String data = comandAndData.substring(2);

            if (SerialCmdEnum.HEARTBEAT.getValue().equals(command)) {
                String state = data.substring(4);
                //串口心跳
                if ("30".equals(state)) {

                } else if ("31".equals(state)) {
                    ToastUtils.showShort("串口未签到");
                } else if ("32".equals(state)) {
                    ToastUtils.showShort("串口有故障");
                } else if ("50".equals(state)) {
                    //进入管理页
                    EventBus.getDefault().post(new CommonEvent(CommonEvent.OPEN_SETTING_LOGIN));
                }
                return;
            }

            if (TextUtils.isEmpty(data)) {
                LogUtil.p("{SerialCmdResponseManager}[handleResponse]: data is empty!!!");
                return;
            }
            //让人能看懂的字符数据
            final String originData = StringUtil.convertHexToString(data);
            LogUtil.i("serialport", "{SerialCmdResponseManager}[handleResponse]" +
                    "response command=" + command + ",data=" + originData);

            if (command.equals(reqeustCmdValue) && resopnseCallback != null) {

                LogUtil.p("收到串口指令：" + command);

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        resopnseCallback.onCallBack(command, originData);
                    }
                });
            }
        } else {
            LogUtil.p("serial check resposne is Fail");
            ToastUtils.showShort("响应解析失败");
        }
    }

    public interface ResopnseCallback {
        void onCallBack(String cmdValue, String data);
    }

}
